/* Copyright(c) 2010- Siro-info Co.(http://www.siro-info.com)
 * All rights reserved.
 */
package com.siro.pm.utils;

import java.sql.Connection;

import org.apache.commons.dbcp.BasicDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Class Declaration:
 * 
 * @version v1.0
 * @since DatabasePool.java v1.0
 */
public class DatabasePool {
	private static final Logger logger = LoggerFactory
			.getLogger(DatabasePool.class);
	static BasicDataSource dataSource = null;

	private static BasicDataSource createDataSource() throws Exception {
		if (logger.isInfoEnabled())
			logger.info("开始建立数据库连接池...");
		String driverClassName = System.getProperty("jdbc.driverClassName");
		String url = System.getProperty("jdbc.url");
		String userName = System.getProperty("jdbc.username");
		String password = System.getProperty("jdbc.password");
		String initialPoolSize = System
				.getProperty("jdbc.initialPoolSize", "1");
		String maxActive = System.getProperty("jdbc.maxActive", "200");
		String maxIdle = System.getProperty("jdbc.maxIdle", "10");
		String minIdle = System.getProperty("jdbc.minIdle", "0");
		String maxWaitTime = System.getProperty("jdbc.maxWait", "20000");

		boolean autoCommit = Boolean.parseBoolean(System.getProperty(
				"jdbc.autoCommit", "true"));
		boolean testonborrow = Boolean.parseBoolean(System.getProperty(
				"jdbc.testonborrow", "false"));
		boolean testwhileidle = Boolean.parseBoolean(System.getProperty(
				"jdbc.testwhileidle", "false"));
		String validationquery = System.getProperty("jdbc.validationquery", "");

		dataSource = new BasicDataSource();
		dataSource.setDriverClassName(driverClassName);
		dataSource.setUrl(url);
		dataSource.setUsername(userName);
		dataSource.setPassword(password);
		if (!initialPoolSize.equals("-1"))
			dataSource.setInitialSize(Integer.parseInt(initialPoolSize));
		if (!maxActive.equals("-1"))
			dataSource.setMaxActive(Integer.parseInt(maxActive));
		if (!maxIdle.equals("-1"))
			dataSource.setMaxIdle(Integer.parseInt(maxIdle));
		if (!minIdle.equals("-1"))
			dataSource.setMinIdle(Integer.parseInt(minIdle));
		if (!maxWaitTime.equals("-1"))
			dataSource.setMaxWait(Long.parseLong(maxWaitTime));
		dataSource.setDefaultAutoCommit(autoCommit);
		dataSource.setTestOnBorrow(testonborrow);
		dataSource.setTestWhileIdle(testwhileidle);
		dataSource.setValidationQuery(validationquery);
		if (logger.isInfoEnabled())
			logger.info("建立数据库连接池成功");
		return dataSource;
	}

	public synchronized static Connection getConnection() throws Exception {
		if (dataSource == null) {
			dataSource = createDataSource();
		}
		return dataSource.getConnection();
	}

}
